package test;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUploader extends HttpServlet {

	private static final long serialVersionUID = 588194926670161680L;

	private int maxPostSize = 100 * 1024 * 1024; 
	private String uploadPath = "D:\\attachmentFile\\";  
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		processRequest(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		processRequest(req, resp);
	}

	protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		         System.out.println("Access !");  
		         response.setContentType("text/html;charset=UTF-8");  
		         PrintWriter out = response.getWriter();  
		         
		         DiskFileItemFactory factory = new DiskFileItemFactory();  
		         factory.setSizeThreshold(4096);  
		         ServletFileUpload upload = new ServletFileUpload(factory);  
		         upload.setSizeMax(maxPostSize);  
		         try {  
		             List fileItems = upload.parseRequest(request);  
		             Iterator iter = fileItems.iterator();  
		             while (iter.hasNext()) {  
		                 FileItem item = (FileItem) iter.next();  
		                 if (!item.isFormField()) {  
		                     String name = item.getName();  
		                     System.out.println(name);  
		                     try {  
		                         item.write(new File(uploadPath + name));
		                     } catch (Exception e) {  
		                         e.printStackTrace();  
		                     }  
		                 }  
		             }  
		         } catch (FileUploadException e) {  
		             e.printStackTrace();  
		             System.out.println(e.getMessage() + "Finished");  
		         }  
	}
}
